<?php

class Admin_CursoController extends App_Controller_Action
{
    private $_table     = 'CURSO';
    private $_pk        = 'CUR_ID';
    private $_order_col = 'CUR_ID';
    private $_order     = 'ASC';
    private $_sta_col   = 'CUR_STA';
    private $obj        = '';
    private $form       = '';
    public  $db       = '';
    
    public function init()
    {
        $this->obj = new Admin_Model_DbTable_Curso();
        if($this->getRequest()->getActionName() == 'edit') $this->form = new Admin_Form_Curso();
        $this->db = Zend_Db_Table_Abstract::getDefaultAdapter();
    }

    public function indexAction() {
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('operacoes','library');
        Zend_Loader::loadClass('dominio','library');
        Zend_Loader::loadClass('elemform','library');
        
        $this->view->headLink()->prependStylesheet($this->_urlbase.'/public/media/js/chosen/chosen.min.css'); 
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/chosen/chosen.jquery.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_curso_list.js');
        
        $where = 'WHERE t.'.$this->_pk . ' > 0';
        
        $itfiltro = $this->_getParam('itfiltro', ''); 
        $anfiltro = $this->_getParam('anfiltro', ''); 
        $stfiltro = $this->_getParam('stfiltro', '1'); 
                
        if($itfiltro != '') $where .= ' and c.CBS_ID = ' . $itfiltro;
        if($anfiltro != '') $where .= ' and t.CUR_ANO = ' . $anfiltro;
        if($stfiltro != '') $where .= ' and t.CUR_STA = ' . $stfiltro;
        
        $this->view->itfiltro = $itfiltro;
        $this->view->anfiltro = $anfiltro;
        $this->view->stfiltro = $stfiltro;
       
        $query = 'SELECT SQL_CACHE t.*,c.CBS_NOM,c.CBS_TPOTMP, n.NRT_NOM '
                .' FROM '.$this->_table.' t ' // , CURSOBASE c , NUMEROTURMA n 
                .' INNER JOIN CURSOBASE c ON t.CBS_ID = c.CBS_ID '
                .' LEFT JOIN NUMEROTURMA n ON n.NRT_ID = CUR_TRM '
                .' '.$where.' ' //and t.CBS_ID = c.CBS_ID  and t.CUR_TRM = n.NRT_ID
                .' ORDER BY c.CBS_NOM ASC, n.NRT_NOM ASC, t.CUR_ANO DESC'; //.$this->_order_col.' '.$this->_order;
        $result = $this->db->fetchAll($query);
        $this->view->result = $this->paginacao($result,20);
    }
    
    public function editAction() {
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskMoney.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskedinput.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/mask.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        
        $this->view->headLink()->prependStylesheet($this->_urlbase.'/public/media/js/chosen/chosen.min.css'); 
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/chosen/chosen.jquery.min.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_curso.js?1=32');
        
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('elemform','library');
        Zend_Loader::loadClass('dominio','library');
        
        $this->view->form = $this->form;
        if($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                
                $this->db->beginTransaction();
                if(1){//$this->form->isValid($formData)) {
                    $id = (int) $formData[$this->_pk];//$this->form->getValue($this->_pk);
                    
                    $data = $formData;//$this->form->getValues();
                    //print_r($data);
                    unset($data['FOR_ID']);
                    unset($data['submit']);
                    
                    if($data['CUR_TPOTMP'] != 2) $data['CUR_SEM'] = 0;
                    else if($data['CUR_TPOTMP'] == 2 && $data['CUR_SEM'] <= 0) $data['CUR_SEM'] = 1;
                    
                    $data['CUR_VLR'] = tools::money_to_float($data['CUR_VLR']); 
                    $data['CUR_DATPRO'] = Datetools::dma_amd($data['CUR_DATPRO']);
                    $data['CUR_PERDSC'] = tools::money_to_float($data['CUR_PERDSC']); 
                    $data['CUR_VLRPRO'] = tools::money_to_float($data['CUR_VLRPRO']); 
                    $data['CUR_DATINI'] = Datetools::dma_amd($data['CUR_DATINI']);
                    $data['CUR_DATFIM'] = Datetools::dma_amd($data['CUR_DATFIM']);
                    
                    $data['MTL_ID'] = implode(',', $data['MTL_ID']);
                    
                    $erro = 0;
                    if ($id == 0){
                        $data['CUR_VAGMAT'] = $data['CUR_NMRMAXALU']; // vagas disponíveis
                        $this->obj->insert($data);
                        $id =  $this->obj->getAdapter()->lastInsertId(); 
                    }
                    else {
                        //$mat = new Admin_Model_DbTable_Matricula();
                        //$r_mat = $mat->fetchRow($this->_pk.' = ' . $id.' and MAT_STA = 1');
                        //if($r_mat['MAT_ID'] <= 0){ // se tiver matricula não altera mais
                            $this->obj->update($data, $this->_pk.' = ' . $id);
                        //}
                        //else $erro = 1;
                    }
                    
                    $obj2 = new Admin_Model_DbTable_Cursoforma();
                    $obj2->delete('CUR_ID = '.(int)$id);
                    foreach($formData['FOR_ID'] as $for)
                    {   
                        $data = array( 'CUR_ID'=> $id, 'FOR_ID'=> $for);
                        $obj2->insert($data);
                    }
                    
                    /*
                    $obj2 = new Admin_Model_DbTable_Cursoturno();
                    $obj2->delete('CUR_ID = '.(int)$id);
                    foreach($this->form->getValue('CRT_ID') as $tur)
                    {   
                        $data = array( 'CRT_ID'=> $tur, 'CUR_ID'=> $id);
                        $obj2->insert($data);
                    }
                    */
                    
                    if($erro == 0){
                        $this->db->commit();
                        $this->_helper->redirector('index');
                    }
                    else{
                        $this->db->rollBack();
                        echo '<script>alert("Curso não pode ser alterado. Matrículas já realizadas!");</script>';
                    }
                } else {
                    //$this->form->populate($formData);
                    $this->view->data = $formData;
                    $this->db->rollBack();
                }
            } catch(Exception $ex) {
                echo '<script>alert("'.$ex->getMessage().'");</script>';
                $this->view->data = $formData;
                $this->db->rollBack();
            }
        } else {
            
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $data = $this->obj->fetchRow($this->_pk . ' = ' . $id)->toArray();
                $data['CUR_VLR'] = tools::float_to_money($data['CUR_VLR']); 
                $data['CUR_DATPRO'] = Datetools::amd_dma($data['CUR_DATPRO']);
                $data['CUR_VLRPRO'] = tools::float_to_money($data['CUR_VLRPRO']); 
                $data['CUR_PERDSC'] = tools::float_to_money($data['CUR_PERDSC']); 
                $data['CUR_DATINI'] = $data['CUR_DATINI'] != '0000-00-00' ? Datetools::amd_dma($data['CUR_DATINI']):'';
                $data['CUR_DATFIM'] = $data['CUR_DATFIM'] != '0000-00-00' ? Datetools::amd_dma($data['CUR_DATFIM']):'';
                
                //$this->form->populate($data);
                $this->view->data = $data;
            }
        }
    }

    public function deleteAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $id = $this->_getParam('id', 0);
        if ((int)$id > 0 ){   
            //$data = array($this->_sta_col => 0);
            //$ok = (bool) $this->obj->update($data, $this->_pk . ' = ' . $id);
            $for = new Admin_Model_DbTable_Cursoforma();
            $ok = (bool) $for->delete($this->_pk . ' = ' . $id);
            $ok = (bool) $this->obj->delete($this->_pk . ' = ' . $id);

        }       
        echo json_encode(array('ok' => $ok));
    }
    
    public function buscacursobaseAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $id = $this->_getParam('cbs_id', 0);
        $cur_id = $this->_getParam('cur_id', 0);
        $tur_id = $this->_getParam('tur_id', 0);
        $ano = $this->_getParam('ano', 0);
        $sem = $this->_getParam('sem', 0);
        
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('dominio','library');
        
        if ((int)$id > 0 ){
            $obj = new Admin_Model_DbTable_Cursobase();
            $data = $obj->fetchRow('CBS_ID = ' . $id);
            
            $obj = new Admin_Model_DbTable_Curso();
            $data_cur = $obj->fetchRow('CUR_ID = ' . $cur_id);
            
            $arr= dominio::TipoSemestre();
            $tipo_curso = $arr[$data['CBS_TPOTMP']];
            
            $arr_cur = array();
            $cur = new Admin_Model_DbTable_Curso();
            $where = '';
            if($tur_id > 0) $where = ' and TUR_ID = '.$tur_id;
            //$r_cur = $cur->fetchAll('CUR_ID <> "'.$data_cur['CUR_ID'].'" and CBS_ID = "'.$data['CBS_ID'].'" and CUR_STA = 1 and CUR_ANO >= '.date('Y').$where);
            $r_cur = $cur->fetchAll('CUR_ID <> "'.$data_cur['CUR_ID'].'" and CBS_ID = "'.$data['CBS_ID'].'" and CUR_STA = 1 and CUR_ANO = '.$ano.' AND CUR_SEM = "'.$sem.'"'.$where); // >= date('Y')
            foreach($r_cur as $r_c) $arr_cur[$r_c['CUR_TRM']] = $r_c['CUR_TRM'];

            $obj = new Admin_Model_DbTable_Numeroturma();
            $obj = $obj->fetchAll();

            $turma = '<select id="CUR_TRM" name="CUR_TRM" class="chosen-select" required=""><option value="">Nenhum</option>';
            foreach($obj as $r){   
                if(array_search($r['NRT_ID'], $arr_cur) === FALSE){
                    $select = $r['NRT_ID'] == $data_cur['CUR_TRM'] ? 'selected':''; 
                    $turma .= '<option '.$select.' value="'.$r['NRT_ID'].'">'.$r['NRT_NOM'].'</option>';
                }
            }
            $turma .= '</select><script> $(function(){ $(".chosen-select").chosen(); }); </script>';
            
           echo json_encode(array('ok' => TRUE,'CUR_TPOTMP'=>$data['CBS_TPOTMP'],
                'tipo_curso'=>$tipo_curso, 'turma' =>$turma,
               ));
            
        }
        else echo json_encode(array('ok' => $ok));
    }
}

